package com.sadhoc.sockets;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.sadhoc.router.PacketReceiver;
import com.sadhoc.router.util.Debug;

public class TCPReceiver implements Runnable {
	
	private ServerSocket socket 	= null;
	private PacketReceiver receiver	= null;
	private int port;
	
	/*
	 * Constructor
	 */
	public TCPReceiver(int port, PacketReceiver receiver) throws IOException {
		
		socket = new ServerSocket(port);
		this.receiver = receiver;
		this.port = port;
		
	}
	
	/*
	 * Listens for TCP connection. When a connection is received it
	 * handles in a new thread with TCPReceiverHandler
	 */
	public void run() {
		
		Debug.printBasic("TCPReceiver now listening on port " + port);
		
        while(!socket.isClosed()) {
        	try {
        		
        		Socket cSocket = socket.accept();
        		TCPReceiverHandler h = new TCPReceiverHandler(cSocket, receiver);
        		new Thread(h).start();

        	} catch (IOException e) {
        		e.printStackTrace();
        	}
        }
        
		Debug.printBasic("TCPReceiver has stopped listening");
		
	}

	/*
	 * Stops the thread by closing the socket
	 */
	public void stop() {
		
		synchronized (socket) {
			try {
				
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			socket.notify();
		}
		
	}
	
}

